package com.archerdu.base.mail;

import java.util.Date;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

public class MailSender {

    private static Logger LOGGER = Logger.getLogger(MailSender.class);

    /**
     * 发送邮件
     * 
     * @param server
     * @param content
     * @param receive
     * @throws AddressException
     * @throws MessagingException
     */
    public static void send(IServerInfo server, IContentInfo content, IReceiveInfo receive) throws AddressException,
            MessagingException {
        LOGGER.debug(receive.getToAddress() + " is to be sended");
        Message message = initialServer(server);
        if(content.isHtml()){
            initialHtmlContent(content, message, content.getEncoding());
        }else{
            initialContent(content, message);
        }
        initialReceive(receive, message);
        Transport.send(message);
        LOGGER.info(receive.getToAddress() + " is be sended successfully");
    }

    /**
     * 初始服务器信息
     * 
     * @param server
     * @return
     * @throws AddressException
     * @throws MessagingException
     */
    private static Message initialServer(IServerInfo server) throws AddressException, MessagingException {
        // 判断是否需要身份认证
        MyAuthenticator authenticator = null;
        if (server.isValidate()) {
            // 如果需要身份认证，则创建一个密码验证器
            authenticator = new MyAuthenticator(server.getUserName(), server.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(server.getProperties(), authenticator);
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 设置邮件消息的发送者
        mailMessage.setFrom(new InternetAddress(server.getFromAddress()));
        return mailMessage;
    }

    /**
     * 初始化邮件内容信息
     * 
     * @param content
     * @param message
     * @throws MessagingException
     */
    private static void initialContent(IContentInfo content, Message message) throws MessagingException {
        // 设置邮件消息的主题
        message.setSubject(content.getSubject());
        // 设置邮件消息的主要内容
        String mailContent = content.getContent();
        message.setText(mailContent);
    }

    /**
     * 初始化邮件内容信息
     * 
     * @param content
     * @param message
     * @param encoding
     * @throws MessagingException
     */
    private static void initialHtmlContent(IContentInfo content, Message message, String encoding)
            throws MessagingException {
        encoding = encoding == null ? "UTF-8" : encoding;
        // 设置邮件消息的主题
        message.setSubject(content.getSubject());
        // 设置邮件消息的主要内容
        // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(content.getContent(), "text/html; charset=" + encoding);
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        message.setContent(mainPart);
    }

    /**
     * 初始化收件人信息
     * 
     * @param receive
     * @param message
     * @throws AddressException
     * @throws MessagingException
     */
    private static void initialReceive(IReceiveInfo receive, Message message) throws AddressException,
            MessagingException {
        // 设置邮件消息发送的时间
        message.setSentDate(new Date());
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receive.getToAddress()));
    }
}
